package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.RecommendVideo;
import com.tanhua.model.mongo.Sound;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/8 0008 下午 2:35
 */
@DubboService
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String saveSound(Sound sound) {
        sound.setVid(idWorker.getNextId("sound"));
        sound.setCreated(System.currentTimeMillis());
        mongoTemplate.save(sound);

        return sound.getId().toHexString();
    }

    @Override
    public Sound findOneByRandom(Long userId) {
        TypedAggregation aggregation = Aggregation.newAggregation(Sound.class, Aggregation.sample(1),Aggregation.match(Criteria.where("userId").nin(userId)));

        AggregationResults<Sound> aggregate = mongoTemplate.aggregate(aggregation, Sound.class);

        return aggregate.getUniqueMappedResult();
    }

    @Override
    public void remove(Sound sound) {
        mongoTemplate.remove(sound);
    }
}
